# coding=utf-8
import os
import platform
from random import shuffle

import pandas as pd
from loguru import logger


def csv2excel_link_main_name_for2(full_path_csv):
    """
    =HYPERLINK("https://xueqiu.com/S/SH600498","111")
    """
    try:
        # https://xueqiu.com/S/SH601066
        s_name = os.path.basename(full_path_csv).split('.')[0]
        df = pd.read_csv(full_path_csv)
        df['code'] = df.apply(lambda row: '"'.join([f'=HYPERLINK(',
                                                    f"https://xueqiu.com/S/{str(row['code']).split('.')[1]}{str(row['code']).split('.')[0]}",
                                                    ',',
                                                    s_name,
                                                    ')']),
                              axis=1)
        ew = pd.ExcelWriter(str(full_path_csv).replace('.csv', '.xlsx'))
        df.to_excel(ew, header=True, index=False)
        if 'mac' in platform.platform().lower():
            ew.save()
        else:
            ew._save()
        os.remove(full_path_csv)
    except Exception as e:
        logger.error(e)


def csv2excel_link(full_path_csv):
    """
    =HYPERLINK("https://xueqiu.com/S/SH600498","111")
    """
    try:
        df = pd.read_csv(full_path_csv)
        df['超链接'] = df.apply(lambda row: '"'.join([f'=HYPERLINK(', str(row['超链接']), ',', str(row['名字']), ')']),
                                axis=1)
        del df['名字']
        ew = pd.ExcelWriter(str(full_path_csv).replace('.csv', '.xlsx'))
        df.to_excel(ew, header=True, index=False)
        ew.save()
        os.remove(full_path_csv)
    except Exception as e:
        print(e)


def csv2excel(full_path_csv):
    try:
        df = pd.read_csv(full_path_csv)
        ew = pd.ExcelWriter(str(full_path_csv).replace('.csv', '.xlsx'))
        df.to_excel(ew, header=True, index=False)
        ew.save()
    except Exception as e:
        print(e)


def sort_csv(full_path_csv, sort_k, ascd):
    try:
        df = pd.read_csv(full_path_csv)
        if sort_k:
            df = df.sort_values(by=sort_k, ascending=ascd)
        df.to_csv(full_path_csv, header=True, index=False)
        print(full_path_csv)
    except Exception as e:
        print(e)

def sort_csv2(save_path, full_path_csv, sort_k, ascd):
    try:
        df = pd.read_csv(full_path_csv)
        if sort_k:
            df = df.sort_values(by=sort_k, ascending=ascd)
        df.to_csv(save_path, header=True, index=False)
        print(save_path)
        # os.remove(full_path_csv)
    except Exception as e:
        print(e)


def read_csv(full_path_csv, filter_ndays=15, select_k='ndays'):
    df = pd.read_csv(full_path_csv)
    return set([f'{d[1]} {d[0]}' for d in df[df[select_k] > filter_ndays].values.tolist()])


if __name__ == '__main__':
    csv2excel_link(r'../result/10_20231222_连跌.csv')
